package com.example.qihuibao.module.service

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.*
import android.util.Log
import com.example.qihuibao.constant.Config
import com.example.qihuibao.utils.ConnectUtil
import com.example.qihuibao.utils.LogUtil
import com.koushikdutta.async.callback.CompletedCallback
import com.koushikdutta.async.http.AsyncHttpClient
import com.koushikdutta.async.http.WebSocket
import com.koushikdutta.async.http.server.AsyncHttpServer
import com.koushikdutta.async.http.server.AsyncHttpServerRequest
import java.lang.ref.WeakReference

/**
 * 设备的侦听&连接
 */
class ConnectService : Service() {
    private var running = true
    private var myHandler:MyHandler? = null
    private var callback:CallBack? = null

    override fun onCreate() {
        super.onCreate()
        startGroupListener()
    }

    override fun onDestroy() {
        super.onDestroy()
        running = false
    }

    override fun onBind(intent: Intent?): IBinder? {
        return MyBinder()
    }

    //侦听（服务站）组播
    private fun startGroupListener() {
        Thread {
            while (running) {
                LogUtil.e("开始侦听组播")
                ConnectUtil.groupReceive {
                    this.callback?.getServerGroup(it)
                }
            }
        }.start()
    }

    fun setCallback(callBack: CallBack) {
        this.callback = callBack
    }

    inner class MyBinder : Binder() {
        fun getService(): ConnectService {
            return this@ConnectService
        }
    }

    interface CallBack {
        fun getServerGroup(message:String)
    }



    private var httpServer: AsyncHttpServer? = null
    private val webSockets = mutableListOf<WebSocket>()
    //启动本地服务
    fun startServer() {
        stopServer()
        httpServer = AsyncHttpServer()
        httpServer?.websocket("/", "") { webSocket, request ->
            webSocket?.setClosedCallback {
                LogUtil.e("close")
            }
        }
        httpServer?.listen(Config.serverPort)
        httpServer?.errorCallback = CompletedCallback { ex ->
            if (ex != null) {
            }
        }
    }

    fun stopServer() {
        httpServer?.stop()
        httpServer = null
        webSockets.clear()
    }

    private var clientWebSocket: WebSocket? = null
    //connect server
    fun startConnect(back:(success:Boolean, msg:String)->Unit, close:()->Unit) {
        stopConnect()
        val url = "ws://${Config.serverIp}:${Config.serverPort}"
        AsyncHttpClient.getDefaultInstance().websocket(url, "") { ex, webSocket ->
            if (ex != null) {
                myHandler?.post { back(false, "${ex.message}") }
                return@websocket
            }
            if (webSocket !=null) {
                myHandler?.post { back(true, "") }
            }
            clientWebSocket = webSocket
        }
    }

    fun stopConnect() {
        clientWebSocket?.closedCallback = null
        clientWebSocket?.close()
        clientWebSocket = null
    }


    /**
     * handler 用于切换主线程
     */
    internal class MyHandler(ctx:Context) : Handler() {
        var activityReference: WeakReference<Context> = WeakReference(ctx)
    }

}